package com.cyy.admin.service;

import com.alibaba.fastjson.JSON;
import com.cyy.admin.entity.CyyUserEntity;
import com.cyy.admin.repository.CyyUserRepository;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 *
 * @author chenyuyi
 * @date 2021-12-01 16:43:08
 */
@Service
public class CyyUserService {

    @Autowired
    private CyyUserRepository cyyUserRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public Object insert(CyyUserEntity cyyUser){
        return cyyUserRepository.save(cyyUser);
    }


    public int updateByPrimaryKey(CyyUserEntity cyyUser) {
        return cyyUserRepository.updateById(cyyUser.getUserName());
    }

    public List<CyyUserEntity> select(CyyUserEntity cyyUser) {
        return cyyUserRepository.findAll();
    }

    public CyyUserEntity findByUserName(String loginName) {
        return cyyUserRepository.findByUserName(loginName);
    }

    public CyyUserEntity findByLoginnameAndPassword(String loginname, String password) {
            CyyUserEntity admin = cyyUserRepository.findByUserName(loginname);
            if(admin != null && bCryptPasswordEncoder.matches(password,admin.getPassword())){
                return admin;
            }else{
                return null;
            }
    }

    public CyyUserEntity getLoginUser(Claims user_claims) {
        //获取缓存中的对象
        if(redisTemplate.opsForValue().get("user") != null){
            CyyUserEntity user = JSON.parseObject(redisTemplate.opsForValue().get("user"),CyyUserEntity.class);
            if(user.getUserId().equals(user_claims.get("jti"))){
                return user;
            }
        }
        return null;
    }
}